import { Injectable } from '@angular/core';
import {fromLonLat, transform} from 'ol/proj';

@Injectable({
  providedIn: 'root'
})
export class LocationSearchService {
  districtSearch: any;

  constructor() { }

  private districtSearchInit() {
    const opts = {
      subdistrict: 1,   // 返回下一级行政区
      showbiz: false,  // 最后一级返回街道信息
      extensions: 'all'
    };
    this.districtSearch = new AMap.DistrictSearch(opts);
  }

  fetchLocationOptions(name = '中国'): Promise<any> {
    if (!this.districtSearch) {
      this.districtSearchInit();
    }
    return new Promise((resolve, reject) => {
      this.districtSearch.search(name, (status, result) => {
        if (status === 'complete') {
          const options = result.districtList[0].districtList.map(value => {
            return { label: value.name, value: value.adcode }
          });
          const boundaries = result.districtList[0].boundaries;
          const center = fromLonLat([result.districtList[0].center.lng, result.districtList[0].center.lat]);
          resolve({ options, boundaries, center });
        }
      })
    })
  }

}
